﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

using Coslen.TahorCRM.UI.www.DependencyResolver;
using Coslen.TahorCRM.UI.www.Helpers;
using Elmah;
using MvcLoggingDemo.Services;
using NLog.Config;

namespace Coslen.TahorCRM.UI.www
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    // Event Info :
    // http://www.techrepublic.com/article/working-with-the-aspnet-globalasax-file/5771721

    public class MvcApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// 
        /// Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.
        /// </summary>
        protected void Application_Start()
        {
            // IOC
            System.Web.Mvc.DependencyResolver.SetResolver(new NinjectDependencyResolver()); // MVC3 way

            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Setup our custom controller factory so that the [HandleErrorWithElmah] attribute
            // is automatically injected into all of the controllers
            ControllerBuilder.Current.SetControllerFactory(new ErrorHandlingControllerFactory());

            // Register custom NLog Layout renderers
            ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("utc_date", typeof(Coslen.Framework.Logging.NLog.UtcDateRenderer));
            ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("web_variables", typeof(Coslen.Framework.Logging.NLog.WebVariablesRenderer));

            // Register the Log4Net
            log4net.Config.DOMConfigurator.Configure();
        }

        /// <summary>
        /// 
        /// Fired when an unhandled exception is encountered within the application.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            HttpException httpException = exception as HttpException;
            // Log this exception with your logger
            //ErrorSignal.FromCurrentContext().Raise(httpException);
        }

        /// <summary>
        /// 
        /// The last event fired for an application request.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_EndRequest(object sender, EventArgs e)
        {
        }

        public void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
        {
            IPrincipal principal = SecurityPrincipalHelper.GetPrincipalFromCacheOrCookie(HttpContext.Current);

            if (principal != null)
            {
                HttpContext.Current.User = principal;
                Thread.CurrentPrincipal = principal;
            }
        }
    }
}